package org.example.demo.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("demo")
public class TestApi {

    @Value("${server.port}")
    private String port;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("testGetString")
    @ResponseBody
    public String aaa(@RequestParam("serverName")String name){
        //127.0.0.1:8086/demo/testGetString?serverName=TWO-SSM-AND-EUREKA
        List<ServiceInstance> ll =  discoveryClient.getInstances(name);
        StringBuilder sb =new StringBuilder() ;
        sb.append("Demo-String").append(port);
        if(Objects.nonNull(ll) && ll.size() >0 ){
            sb.append( "---").append(name);
            sb.append(":");
            sb.append(ll.stream().map(si-> si.getHost()+":"+si.getPort()).collect(Collectors.joining(",")));

        }
        return sb.toString();

    }

    @GetMapping("/testPrivate")
    private String testPrivate(){
        /****
         * see https://blog.csdn.net/qq_36776608/article/details/144460931
         * 看看为什么 私有方法也可以提供服务
         */
        //127.0.0.1:8086/demo/testPrivate
        return "11111";
    }
}
